package city.spring.service.mealService.impl;

import city.spring.domain.entity.mealService.FoodInfoEntity;
import city.spring.domain.entity.mealService.FoodTypeEntity;
import city.spring.repository.mealService.FoodTypeRepository;
import city.spring.service.mealService.FoodInfoService;
import city.spring.service.mealService.FoodTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Transactional(rollbackFor = Throwable.class)
@Service
public class FoodTypeServiceImpl extends ServiceImpl<FoodTypeRepository, FoodTypeEntity> implements FoodTypeService {

    private final FoodInfoService foodInfoService;

    public FoodTypeServiceImpl(FoodInfoService foodInfoService) {
        this.foodInfoService = foodInfoService;
    }

    @Override
    public void saveFoodType(FoodTypeEntity entity) {
        boolean save = save(entity);
        if (!save) {
            throw new RuntimeException("保存食品类型失败");
        }
    }

    @Override
    public void updateFoodType(FoodTypeEntity entity) {
        FoodTypeEntity oldEntity = getById(entity.getId());
        boolean update = lambdaUpdate()
                .set(FoodTypeEntity::getType, entity.getType())
                .set(FoodTypeEntity::getTypeCode, entity.getTypeCode())
                .eq(FoodTypeEntity::getId, entity.getId())
                .update();
        if (!update) {
            throw new RuntimeException("修改食物类型失败");
        }
        if (!StringUtils.equals(oldEntity.getTypeCode(), entity.getTypeCode())) {
            // 数据字典类型已经被修改，需要手动维护原来旧的类型值列表
            foodInfoService.lambdaUpdate()
                    .set(FoodInfoEntity::getFoodId, entity.getTypeCode())
                    .eq(FoodInfoEntity::getFoodId, oldEntity.getTypeCode())
                    .update();
        }
    }

    @Override
    public void deleteFoodType(String primaryKey) {
        removeById(primaryKey);
        foodInfoService.lambdaUpdate().eq(FoodInfoEntity::getFoodId, primaryKey).remove();
    }

    @Override
    public void deleteFoodType(List<String> primaryKeys) {
        removeByIds(primaryKeys);
        foodInfoService.lambdaUpdate()
                .in(FoodInfoEntity::getFoodId, primaryKeys)
                .remove();
    }

}
